import { useEffect, useState } from "react";
import { Button, Card, Drawer, Form, Input, Space, Spin, Upload } from "antd";
import type { ColumnsType } from "antd/es/table";
import appVersionService, { type PageListReq } from "@/api/services/tool/appVersionService";
import type { SopAppVersion } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";
import CustomTable from "@/components/grid/CustomTable";
import type { UploadFile, UploadProps } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import React from "react";

export default function SopAppVersionPage() {
	const [loading, setLoading] = useState(false);
	const [submitLoading, setSubmitLoading] = useState(false);
	const [queryParams, setQueryParams] = useState<PageListReq>({
		version: undefined,
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<SopAppVersion[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [editingData, setEditingData] = useState<SopAppVersion | null>(null);
	const [form] = Form.useForm();
	const [isView, setIsView] = useState(true);

	const [fileList, setFileList] = useState<UploadFile[]>([]);

	//动态设置表格高度
	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 405;
	const updateTableHeight = () => {
		const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
		setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
	};

	useEffect(() => {
		updateTableHeight(); // 初始化
		window.addEventListener("resize", updateTableHeight);
		return () => window.removeEventListener("resize", updateTableHeight);
	}, []);

	const columns: ColumnsType<SopAppVersion> = [
		{
			title: "版本号",
			width: 120,
			key: "version",
			dataIndex: "version",
		},
		{
			title: "文件路径",
			width: 120,
			key: "filePath",
			dataIndex: "filePath",
		},
		{
			title: "操作",
			fixed: "right",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => handleEdit(record)}>
						{t("common.edit")}
					</Button>
					<Button type="link" onClick={() => handleDownLoad(record.id)}>
						下载
					</Button>
				</Space>
			),
		},
	];

	//加载表格数据
	const fetchPageList = () => {
		setLoading(true);
		appVersionService
			.pageList(queryParams)
			.then((res) => {
				setList(res.records);
				setTotal(res.total);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		fetchPageList();
	}, [queryParams]);

	//选择其他页
	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	//触发编辑按钮
	const handleEdit = (sopAppVersion: SopAppVersion) => {
		setEditingData(sopAppVersion);

		setFileList([
			{
				uid: "-1",
				name: sopAppVersion.fileName || "",
				status: "done",
				url: sopAppVersion.filePath,
			},
		]);
		form.setFieldsValue(sopAppVersion);
		setDrawerVisible(true);
		setIsView(false);
	};

	//下载文件
	const handleDownLoad = (attachmentId: React.Key) => {
		appVersionService.downloadFile(attachmentId);
	};

	//提交表单数据
	const handleSubmit = async (values: SopAppVersion) => {
		setSubmitLoading(true);

		const data: any = {
			...values,
			id: editingData?.id,
		};

		try {
			setSubmitLoading(true);
			if (editingData) {
				await appVersionService.update(data);
				toast.success("更新sop版本管理成功");
			} else {
				await appVersionService.add(data);
				toast.success("创建sop版本管理成功");
			}
			setDrawerVisible(false);
			setEditingData(null);
			form.resetFields();
			fetchPageList();
		} catch (error) {
			toast.error(`保存失败: ${error.message}`);
		} finally {
			setSubmitLoading(false);
		}
	};

	const handleDrawerClose = () => {
		setDrawerVisible(false);
		setEditingData(null);
		form.resetFields();
	};

	const handleAdd = () => {
		setEditingData(null);
		form.resetFields();
		setDrawerVisible(true);
		setFileList([]);
		setIsView(false);
	};

	const handleDelete = async () => {
		try {
			setLoading(true);
			await appVersionService.remove(selectedRowKeys);
			toast.success("删除sop版本管理成功");
			setSelectedRowKeys([]);
			fetchPageList();
		} catch (error) {
			toast.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	// 上传前检查
	const beforeUpload = (file: File) => {
		const isApk = file.name.toLowerCase().endsWith(".apk");
		if (!isApk) {
			toast.error("请上传apk文件");
			return false;
		}
		return true;
	};

	// 处理文件列表变化
	const handleFileListChange: UploadProps["onChange"] = (info) => {
		const newFileList = info.fileList.map((file) => ({
			...file,
			// 尽量显式拷贝每个字段
			uid: file.uid,
			name: file.name,
			status: file.status,
			url: file.url,
			response: file.response,
		}));

		setFileList(newFileList);

		const { status } = info.file;
		if (status === "done") {
			const path = info.file.response?.data;
			toast.success(`${info.file.name} 上传成功！`);
			form.setFieldsValue({
				fileName: info.file.name,
				filePath: path,
			});
		} else if (status === "error") {
			toast.error(`${info.file.name} 上传失败！`);
		} else if (status === "removed") {
			const path = info.file.url;
			if (!path) {
				toast.error("文件路径不存在，无法删除！");
				return;
			}
			// 调用接口删除文件
			appVersionService.deleteFile(path);
			form.setFieldsValue({
				fileName: "",
				filePath: "",
			});
			toast.success(`${info.file.name} 删除成功！`);
		}
	};

	return (
		<Spin spinning={submitLoading} tip="数据提交中..." size="large">
			<Card className="mb-4">
				<Form
					layout="inline"
					onFinish={(values) => {
						setQueryParams((prev) => ({
							...prev,
							...values,
							page: 1,
						}));
					}}
				>
					<Form.Item name="version" label="版本号">
						<Input placeholder="请输入版本号" allowClear />
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button
							className="ml-2"
							onClick={() => {
								setQueryParams({ page: 1, pageSize: 10 });
							}}
						>
							重置
						</Button>
					</Form.Item>
				</Form>
			</Card>
			<div className="h-4" />
			<Card>
				<CustomTable
					loading={loading}
					columnsConfig={columns}
					dataSource={list}
					total={total}
					selectedRowKeys={selectedRowKeys}
					setSelectedRowKeys={setSelectedRowKeys}
					current={queryParams.page}
					pageSize={queryParams.pageSize}
					onRefresh={fetchPageList}
					onPageChange={handlePageChange}
					selectable
					toolbarButtons={
						<>
							<Button type="primary" onClick={handleAdd}>
								新增
							</Button>
							<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
								删除
							</Button>
						</>
					}
					scroll={{ y: tableScrollY }}
				/>
			</Card>
			<Drawer
				title={editingData ? "编辑sop版本管理" : "新增sop版本管理"}
				width={500}
				open={drawerVisible}
				onClose={handleDrawerClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleDrawerClose}>取消</Button>
						{!isView && (
							<Button type="primary" loading={submitLoading} onClick={() => form.submit()}>
								确定
							</Button>
						)}
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
					<Form.Item name="version" label="版本号">
						<Input placeholder="请输入版本号" allowClear />
					</Form.Item>
					<Form.Item name="filePath" label="文件路径" style={{ display: "none" }}>
						<Input />
					</Form.Item>
					<Form.Item name="fileName" label="文件名称">
						<Input disabled />
					</Form.Item>

					<Form.Item name="filePath" label="文件">
						<Upload
							name="file"
							multiple={false}
							action="/api/tool/sop/version/upload"
							beforeUpload={beforeUpload}
							onChange={handleFileListChange}
							fileList={fileList}
							maxCount={1}
						>
							<Button icon={<UploadOutlined />}>上传</Button>
						</Upload>
					</Form.Item>
				</Form>
			</Drawer>
		</Spin>
	);
}
